from app01.utils.bootstrap import BootStrapModelForm
from django import forms
from app01 import models
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError
from django.contrib.auth.hashers import make_password

from app01.utils.common import md5_encrypt


class UserForm(BootStrapModelForm):
    name = forms.CharField(min_length=2,label="用户名")
    class Meta:
        model = models.UserInfo
        fields = ["name","password","age","gender","account","create_time","depart"]

    def save(self, commit=True):
        user = super().save(commit=False)
        user.password = md5_encrypt(self.cleaned_data["password"])
        # user.password = make_password(self.cleaned_data["password"])
        if commit:
            user.save()
        return user

class PrettyForm(BootStrapModelForm):
    # 验证方式 1
    phone = forms.CharField(
        label = "手机号码",
        validators=[RegexValidator(r'^1[3-9]\d{9}$','数字必须以159开头')]
    )
    class Meta:
        model = models.PrettyNum
        fields = ["phone","price","level","status"]

    # 验证方式 2
    def clean_phone(self):
        txt_phone = self.cleaned_data["phone"]
        if len(txt_phone) != 11:
            raise ValidationError("手机号码必须为11位数字")
        exists = models.PrettyNum.objects.filter(phone=txt_phone).exists()
        if exists:
            raise ValidationError("手机号码已存在")
        return txt_phone


class PrettyEditForm(BootStrapModelForm):
    # 验证方式 1
    phone = forms.CharField(
        label = "手机号码",
        validators=[RegexValidator(r'^1[3-9]\d{9}$','数字必须以159开头')]
    )
    phone = forms.CharField(disabled=True,label="手机号码")
    class Meta:
        model = models.PrettyNum
        fields = ["phone","price","level","status"]

    # 验证方式 2
    def clean_phone(self):
        txt_phone = self.cleaned_data["phone"]
        if len(txt_phone) != 11:
            raise ValidationError("手机号码必须为11位数字")
        exists = models.PrettyNum.objects.exclude(id=self.instance.pk).filter(phone=txt_phone).exists()
        if exists:
            raise ValidationError("手机号码已存在")
        return txt_phone

class AdminForm(BootStrapModelForm):
    confirm_password = forms.CharField(
        label="确认密码",
        widget=forms.PasswordInput
    )
    class Meta:
        model = models.Admin
        fields = ["username","password","confirm_password"]
        widgets ={
            "password":forms.PasswordInput(render_value=True)
        }

    def clean_confirm_password(self):
        password = self.cleaned_data.get('password')
        confirm = self.cleaned_data.get('confirm_password')
        if password != confirm:
            raise ValidationError("密码不一致")
        new_password = encrypt_password(password)  # MD5加密
        return new_password  #返回值保存到数据库
